from os import name
from celery import shared_task
from .app import app
from copy import deepcopy
from .planner import Planner


def fake_compute(dataset):
    import copy
    import time
    time.sleep(5)
    return copy.deepcopy(dataset)


def real_compute(payload):
    # 1 payload preprocessing
    # task_payload_format-> algo_api_payload_format
    # import requests
    # requests.post('https://lite.doraclp.cn/api/v2/plan/',json=payload)
    # 2 call algorithm web api
    # 3 result postpocessing
    data = deepcopy(payload)

    planner = Planner(
        algo_type=data['config']['algo_type'],
        num_beams=data['config']['num_beams'],
        selected_container=data['config']['container'],
    )

    # 计算
    return planner.compute(data['input_dataset'])


@shared_task(name="zmm.do_compute")
def on_task_compute(payload):
    try:
        # 通知计算任务已经开始
        app.send_task('zmm.do_start',[payload])

        # 执行计算
        # TODO：实现真正的计算逻辑，现在搞个假的
        #result =fake_compute(payload['input_dataset'])
        # 使用真实计算器
        result = real_compute(payload)

        # 通知计算任务已经结束
        payload['result_dataset']=result
        app.send_task('zmm.do_finish',[payload])
    except Exception as e:
        # 通知计算任务已经出错
        app.send_task('zmm.do_fail',[payload])
        raise e